package com.yst.metho.web.application.menu;

import java.io.File;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;

import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.app.Button;
import nextapp.echo2.app.Extent;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.webcontainer.command.BrowserRedirectCommand;

import com.yst.metho.web.application.SuiviProdApp;
import com.yst.metho.web.application.components.GenericEditWindow;
import com.yst.metho.web.application.pointage.SelectMonthPane;
import com.yst.metho.web.application.pointage.SelectUserWeekPane;
import com.yst.metho.web.application.pointage.SelectWeekPane;
import com.yst.metho.web.application.pointage.SelectYearPane;
import com.yst.metho.web.application.reports.DeleteReportAction;
import com.yst.metho.web.application.reports.GenerateReportAction;
import com.yst.metho.web.application.reports.ReportGenerationPane;
import com.yst.metho.web.application.reports.ReportListModel;
import com.yst.metho.web.application.reports.ReportListPane;
import com.yst.metho.web.application.reports.ReportPane;
import com.yst.metho.web.application.user.ChangePwdPane;
import com.yst.metho.web.application.utils.ExceptionMgt;
import com.yst.metho.web.application.utils.Locator;
import com.yst.metho.web.servlet.ReportServlet;
import com.yst.suivi.data.reports.ReportBean;
import com.yst.suivi.data.user.User;
import com.yst.suivi.util.Repository;

public class MenuActionController implements ActionListener
{

	public void actionPerformed(ActionEvent event)
	{
		try
		{
			if (event.getActionCommand().equals("changePwd"))
			{
				changePwd();
			}
			else if (event.getActionCommand().equals("exit"))
			{
				ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand("logout"));
			}
			else if (event.getActionCommand().equals("WeeklyReport"))
			{
				generateWeeklyReport();
			}
			else if (event.getActionCommand().equals("WeeklyReportFor"))
			{
				generateWeeklyReportFor(null);
			}
			else if (event.getActionCommand().equals("ActiveUserWeeklyReport"))
			{
				generateActiveUserWeeklyReport();
			}
			else if (event.getActionCommand().equals("CloseWeekFor"))
			{
				closeWeekFor();
			}
			else if (event.getActionCommand().equals("CloseWeekForAll"))
			{
				closeWeekForAll();
			}
			else if (event.getActionCommand().equals("OpenWeekFor"))
			{
				openWeekFor();
			}
			else if (event.getActionCommand().equals("OpenWeekForAll"))
			{
				openWeekForAll();
			}
			else if (event.getActionCommand().equals("YearlyReport"))
			{
				generateYearlyReport();
			}
			else if (event.getActionCommand().equals("MonthlyReport"))
			{
				generateMonthlyReport();
			}
			else if (event.getActionCommand().equals("CreateReport"))
			{
				createReport();
			}
			else if (event.getActionCommand().equals("DeleteReportGlobal"))
			{
				deleteReport(ReportBean.GLOBAL_REPORT);
			}
			else if (event.getActionCommand().equals("DeleteReportProjet"))
			{
				deleteReport(ReportBean.PROJECT_REPORT);
			}
			else if (event.getActionCommand().equals("GenerateReport"))
			{
				generateReport();
			}
			else if (event.getActionCommand().equals("WeeklySheetReport"))
			{
				generateFullWeeklyReport();
			}
			else
			{
				System.out.println("Action menu for " + event.getActionCommand() + " unknonwn");
			}
		}
		catch (Throwable t)
		{
			ExceptionMgt.manage(t);
		}
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateWeeklyReport() throws FinderException, NamingException, CreateException
	{
		User usr = Locator.getUserView().findByLogin(SuiviProdApp.getApp().getLoggedUser());
		generateWeeklyReportFor(usr);
	}

	private void openWeekFor() throws NamingException, FinderException, CreateException
	{
		final SelectUserWeekPane view = new SelectUserWeekPane(Locator.getUserView().findAllUserActive(), null);
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				if (null == view.getUser())
				{
					ExceptionMgt.displayMessageBox("Vous devez selectionner un utilisateur.");
				}
				else
				{

					try
					{
						Locator.getPointageView().openWeek(view.getSelectedDay(), view.getUser());
					}
					catch (Throwable e)
					{
						ExceptionMgt.manage(e);
					}
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine a activer", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	private void createReport() throws NamingException, FinderException, CreateException
	{
		final ReportPane view = new ReportPane(null);
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					if (view.isFileTransfered())
					{
						Locator.getReportView().createReport(view.getNom(), view.getPath(), view.getInnerFileName(), view.getType());
						File dir = new File(Repository.getRealPath(view.getNom()));
						dir.mkdir();
						StringTokenizer st = new StringTokenizer(view.getInnerFileName(), ReportPane.FILE_SEPARATOR);
						File sourceFile;
						File destFile;
						while (st.hasMoreTokens())
						{
							sourceFile = new File(Repository.getRealPath(st.nextToken()));
							destFile = new File(Repository.getRealPath(view.getNom() + File.separator + sourceFile.getName()));
							ReportPane.copyToFile(sourceFile, destFile);
							if (!sourceFile.delete())
							{
								sourceFile.deleteOnExit();
							}
							GenerateReportAction.compileReport(destFile.getParentFile().getName() + File.separator + destFile.getName());
						}
					}
					else
					{
						ExceptionMgt.displayMessageBox("Vous devez selectionner un fichier");
					}
				}
				catch (Throwable e)
				{
					e.printStackTrace();
					ExceptionMgt.manage(e);
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Ajout d'un rapport", btn);
		window.setHeight(new Extent(230, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	private void deleteReport(int type) throws NamingException, FinderException, CreateException
	{
		ReportListModel model = new ReportListModel(type);
		model.refresh();
		final ReportListPane view = new ReportListPane(model);
		DeleteReportAction btn = new DeleteReportAction(model);
		GenericEditWindow window = new GenericEditWindow(view, "Suppression d'un rapport", btn);
		view.getSelectionModel().addChangeListener(btn);
		window.setHeight(new Extent(230, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	private void generateReport() throws NamingException, FinderException, CreateException
	{
		ReportListModel model = new ReportListModel(ReportBean.GLOBAL_REPORT);
		model.refresh();
		ReportGenerationPane view = new ReportGenerationPane(model);
		GenerateReportAction btn = new GenerateReportAction(model, view);
		view.getSelectionModel().addChangeListener(btn);
		GenericEditWindow window = new GenericEditWindow(view, "Generation d'un rapport", btn);
		window.setHeight(new Extent(230, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	private void closeWeekFor() throws NamingException, FinderException, CreateException
	{
		final SelectUserWeekPane view = new SelectUserWeekPane(Locator.getUserView().findAllUserActive(), null);
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				if (null == view.getUser())
				{
					ExceptionMgt.displayMessageBox("Vous devez selectionner un utilisateur.");
				}
				else
				{

					try
					{
						Locator.getPointageView().closeWeek(view.getSelectedDay(), view.getUser());
					}
					catch (Throwable e)
					{
						ExceptionMgt.manage(e);
					}
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine a cloturer", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	private void closeWeekForAll() throws NamingException, FinderException, CreateException
	{
		// final SelectUserWeekPane view = new
		// SelectUserWeekPane(Locator.getUserView().findAllUserActive(), null);
		final SelectWeekPane view = new SelectWeekPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					// recuperation de tous les utilisateurs
					Collection col = Locator.getUserView().findAllUserActive();
					Iterator it = col.iterator();
					User usr;
					while (it.hasNext())
					{
						usr = (User) it.next();
						Locator.getPointageView().closeWeek(view.getSelectedDay(), usr);
					}
				}
				catch (Throwable e)
				{
					ExceptionMgt.manage(e);
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine a cloturer", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}
	
	private void openWeekForAll() throws NamingException, FinderException, CreateException
	{
		final SelectWeekPane view = new SelectWeekPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					// recuperation de tous les utilisateurs
					Collection col = Locator.getUserView().findAllUserActive();
					Iterator it = col.iterator();
					User usr;
					while (it.hasNext())
					{
						usr = (User) it.next();
						Locator.getPointageView().openWeek(view.getSelectedDay(), usr);
					}
				}
				catch (Throwable e)
				{
					ExceptionMgt.manage(e);
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine a activer", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateActiveUserWeeklyReport() throws FinderException, NamingException, CreateException
	{

		final SelectWeekPane view = new SelectWeekPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				Calendar cal = view.getSelectedDay();
				String reportUrl = "report?rapport={0}&jour={1}&mois={2}&annee={3}";
				String[] params = new String[5];
				params[0] = ReportServlet.ACTIVE_USER_WEEKLY_REPORT;
				params[1] = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
				params[2] = Integer.toString(cal.get(Calendar.MONTH));
				params[3] = Integer.toString(cal.get(Calendar.YEAR));

				ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand(MessageFormat.format(reportUrl, params)));

			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateFullWeeklyReport() throws FinderException, NamingException, CreateException
	{

		final SelectWeekPane view = new SelectWeekPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				Calendar cal = view.getSelectedDay();
				String reportUrl = "report?rapport={0}&jour={1}&mois={2}&annee={3}";
				String[] params = new String[5];
				params[0] = ReportServlet.FULL_WEEKLY_REPORT;
				params[1] = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
				params[2] = Integer.toString(cal.get(Calendar.MONTH));
				params[3] = Integer.toString(cal.get(Calendar.YEAR));

				ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand(MessageFormat.format(reportUrl, params)));

			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateWeeklyReportFor(User usr) throws FinderException, NamingException, CreateException
	{

		final SelectUserWeekPane view = new SelectUserWeekPane(Locator.getUserView().findAllUserActive(), usr);
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				if (null == view.getUser())
				{
					ExceptionMgt.displayMessageBox("Vous devez selectionner un utilisateur.");
				}
				else
				{
					Calendar cal = view.getSelectedDay();
					String reportUrl = "report?rapport={0}&jour={1}&mois={2}&annee={3}&u={4}";
					String[] params = new String[5];
					params[0] = ReportServlet.WEEKLY_REPORT;
					params[1] = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
					params[2] = Integer.toString(cal.get(Calendar.MONTH));
					params[3] = Integer.toString(cal.get(Calendar.YEAR));
					params[4] = view.getUser().getLogin();

					ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand(MessageFormat.format(reportUrl, params)));
				}

			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de la semaine", btn);
		window.setHeight(new Extent(350, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateYearlyReport() throws FinderException, NamingException, CreateException
	{

		final SelectYearPane view = new SelectYearPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{

				String reportUrl = "report?rapport={0}&annee={1}";
				String[] params = new String[2];
				params[0] = ReportServlet.YEARLY_REPORT;
				params[1] = Integer.toString(view.getSelectedDay());

				ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand(MessageFormat.format(reportUrl, params)));

			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Choix de l'annee", btn);
		window.setHeight(new Extent(150, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * @throws CreateException
	 * @throws NamingException
	 * @throws FinderException
	 * 
	 */
	private void generateMonthlyReport() throws FinderException, NamingException, CreateException
	{

		final SelectMonthPane view = new SelectMonthPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{

				String reportUrl = "report?rapport={0}&annee={1}&mois={2}";
				String[] params = new String[3];
				params[0] = ReportServlet.MONTHLY_REPORT;
				params[1] = Integer.toString(view.getSelectedDay());
				params[2] = Integer.toString(view.getSelectedMonth());

				ApplicationInstance.getActive().enqueueCommand(new BrowserRedirectCommand(MessageFormat.format(reportUrl, params)));

			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Rapport mensuel", btn);
		window.setHeight(new Extent(150, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}

	/**
	 * Methode qui affiche la popup de changement de mot de passe de
	 * l'utilisateur connecte.
	 * 
	 */
	private void changePwd()
	{
		final ChangePwdPane view = new ChangePwdPane();
		Button btn = new Button("Ok");
		btn.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent arg0)
			{
				try
				{
					Locator.getUserView().changePwd(view.getOldPwd(), view.getNewPwd(), view.getNewPwdConf());
				}
				catch (NamingException e)
				{
					throw new RuntimeException(e);
				}
				catch (FinderException e)
				{
					throw new RuntimeException(e);
				}
				catch (CreateException e)
				{
					throw new RuntimeException(e);
				}
			}
		});
		GenericEditWindow window = new GenericEditWindow(view, "Changement mot de passe", btn);
		window.setHeight(new Extent(200, Extent.PX));
		SuiviProdApp.getApp().getDefaultWindow().getContent().add(window);
	}
}
